<template>
  <div class="equipment-manage">
    <h2>装备管理</h2>
    <!-- 新增装备按钮 -->
    <el-button type="success" @click="addEquipmentDialogVisible = true" style="margin-bottom: 15px;">新增装备</el-button>

    <!-- 搜索框 -->
    <el-input v-model="searchQuery" placeholder="请输入装备名称" clearable style="width: 300px; margin-bottom: 15px;" @clear="onSearchClear" />
    <el-button type="primary" @click="onSearch">搜索</el-button>

    <!-- 角色装备管理（新增区域） -->
    <div class="role-equipment-manage" style="margin-top: 20px;">
      <h3>角色装备管理</h3>
      <el-input v-model="roleId" placeholder="请输入角色ID" style="width: 200px; margin-right: 10px;"></el-input>
      <el-button type="primary" @click="loadRoleEquipments">加载角色装备</el-button>

      <div v-if="roleEquipments.length > 0" style="margin-top: 10px;">
        <h4>已装备列表</h4>
        <el-tag
            v-for="equipment in roleEquipments"
            :key="equipment.id"
            closable
            @close="removeEquipmentFromRole(equipment.id)"
        >
          {{ equipment.name }}
        </el-tag>
      </div>
    </div>

    <!-- 装备表格 -->
    <el-table :data="equipments.records" style="width: 100%" border v-loading="loading">
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="name" label="装备名称" align="center"></el-table-column>
      <el-table-column label="属性加成" align="center">
        <template #default="scope">
          <span v-for="(value, key) in parseAttribute(scope.row.attributeModifier)" :key="key">
            {{ key }}: {{ value }}
            <br />
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="appearance" label="外观描述" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <!-- 添加装备到角色按钮 -->
          <el-button
              size="small"
              type="success"
              @click="addEquipmentToRole(scope.row.id)"
              v-if="isValidRoleId && !isEquipmentInRole(scope.row.id)"
          >
            添加到角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="equipments.page"
        :page-sizes="[10, 20, 50]"
        :page-size="equipments.rows"
        layout="total, sizes, prev, pager, next, jumper"
        :total="equipments.total"
        style="margin-top: 20px"
    ></el-pagination>

    <!-- 新增装备对话框 -->
    <el-dialog title="新增装备" v-model="addEquipmentDialogVisible" width="30%">
      <el-form :model="newEquipment" :rules="rules" ref="addFormRef">
        <el-form-item label="装备名称" prop="name">
          <el-input v-model="newEquipment.name"></el-input>
        </el-form-item>
        <el-form-item label="属性加成" prop="attributeModifier">
          <el-input type="textarea" v-model="newEquipment.attributeModifier"></el-input>
        </el-form-item>
        <el-form-item label="外观描述" prop="appearance">
          <el-input type="textarea" v-model="newEquipment.appearance"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addEquipmentDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addEquipment">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑装备对话框 -->
    <el-dialog title="编辑装备" v-model="editEquipmentDialogVisible" width="30%">
      <el-form :model="currentEquipment" :rules="rules" ref="editFormRef">
        <el-form-item label="装备名称" prop="name">
          <el-input v-model="currentEquipment.name"></el-input>
        </el-form-item>
        <el-form-item label="属性加成" prop="attributeModifier">
          <el-input type="textarea" v-model="currentEquipment.attributeModifier"></el-input>
        </el-form-item>
        <el-form-item label="外观描述" prop="appearance">
          <el-input type="textarea" v-model="currentEquipment.appearance"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editEquipmentDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateEquipment">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看装备详情对话框（新增） -->
    <el-dialog title="装备详情" v-model="viewEquipmentDialogVisible" width="30%">
      <el-form :model="viewEquipment">
        <el-form-item label="装备名称">
          <el-input v-model="viewEquipment.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="属性加成">
          <el-input type="textarea" v-model="viewEquipment.attributeModifier" disabled></el-input>
        </el-form-item>
        <el-form-item label="外观描述">
          <el-input type="textarea" v-model="viewEquipment.appearance" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewEquipmentDialogVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

// 数据定义 - 适配后端分页结构
const equipments = ref({
  page: 1,
  rows: 10,
  total: 0,
  records: []
});
const searchQuery = ref("");
const loading = ref(false);

// 角色装备管理（新增）
const roleId = ref("");
const roleEquipments = ref([]);
const viewEquipmentDialogVisible = ref(false);
const viewEquipment = ref({});

// 计算属性：验证角色ID是否有效
const isValidRoleId = computed(() => {
  const id = parseInt(roleId.value, 10);
  return !isNaN(id) && id > 0;
});

// 表单相关
const newEquipment = ref({ name: "", attributeModifier: "", appearance: "" });
const currentEquipment = ref({ name: "", attributeModifier: "", appearance: "" });
const addEquipmentDialogVisible = ref(false);
const editEquipmentDialogVisible = ref(false);

// 表单验证规则
const rules = {
  name: [{ required: true, message: "装备名称不能为空", trigger: "blur" }],
  attributeModifier: [
    { required: true, message: "属性加成不能为空", trigger: "blur" },
    { validator: validateAttributeFormat, trigger: "blur" }
  ],
  appearance: [{ required: true, message: "外观描述不能为空", trigger: "blur" }]
};

function validateAttributeFormat(rule, value, callback) {
  try {
    JSON.parse(value);
    callback();
  } catch (e) {
    callback(new Error("属性加成必须是合法的 JSON 格式"));
  }
}

// 属性加成解析函数
function parseAttribute(attrStr) {
  try {
    return JSON.parse(attrStr);
  } catch (e) {
    return {};
  }
}

// 判断装备是否已在角色中（新增）
function isEquipmentInRole(equipmentId) {
  console.log('Checking equipment:', equipmentId, 'in', roleEquipments.value);
  return roleEquipments.value.some(equipment => equipment.id === equipmentId);
}

// 获取装备列表
async function getEquipments() {
  loading.value = true;
  try {
    console.log('Request params:', {
      keyword: searchQuery.value,
      page: equipments.value.page,
      pageSize: equipments.value.rows
    });

    const res = await request.get("/equipments", {
      params: {
        keyword: searchQuery.value,
        page: equipments.value.page,
        pageSize: equipments.value.rows
      }
    });

    if (res.code === 200) {
      equipments.value = res.data || { page: 1, rows: 10, total: 0, records: [] };
      console.log('Fetched equipments:', equipments.value);
    } else {
      ElMessage.error(res.message || "获取装备列表失败");
    }
  } catch (error) {
    handleApiError(error);
  } finally {
    loading.value = false;
  }
}

// 根据ID获取装备（新增）
async function getEquipmentById(equipmentId) {
  try {
    const res = await request.get(`/equipment/${equipmentId}`);
    if (res.code === 200) {
      viewEquipment.value = res.data;
      viewEquipmentDialogVisible.value = true;
    } else {
      ElMessage.error(res.message || "获取装备详情失败");
    }
  } catch (error) {
    handleApiError(error);
  }
}

// 获取角色的所有装备（新增）
async function loadRoleEquipments() {
  if (!isValidRoleId.value) {
    ElMessage.warning("请输入有效的角色ID");
    return;
  }

  try {
    const roleIdNum = parseInt(roleId.value, 10);
    console.log('Loading equipments for role:', roleIdNum);

    const res = await request.get(`/role/${roleIdNum}/equipments`);
    console.log('Role equipments response:', res);

    if (res.code === 200) {
      roleEquipments.value = res.data || [];
      ElMessage.success("加载角色装备成功");
    } else {
      ElMessage.error(res.message || "加载角色装备失败");
    }
  } catch (error) {
    handleApiError(error);
  }
}

// 添加装备到角色（新增）
async function addEquipmentToRole(equipmentId) {
  if (!isValidRoleId.value) {
    ElMessage.warning("请先输入有效的角色ID并加载角色装备");
    return;
  }

  try {
    const roleIdNum = parseInt(roleId.value, 10);
    console.log('Adding equipment:', equipmentId, 'to role:', roleIdNum);

    const res = await request.post(`/role/${roleIdNum}/equipment/${equipmentId}`);
    console.log('Add equipment response:', res);

    if (res.code === 200) {
      ElMessage.success("添加装备到角色成功");
      await loadRoleEquipments(); // 刷新角色装备列表
    } else {
      ElMessage.error(res.message || "添加装备到角色失败");
    }
  } catch (error) {
    handleApiError(error);
  }
}

// 从角色移除装备（新增）
async function removeEquipmentFromRole(equipmentId) {
  if (!isValidRoleId.value) {
    ElMessage.warning("请先输入有效的角色ID");
    return;
  }

  try {
    const roleIdNum = parseInt(roleId.value, 10);
    console.log('Removing equipment:', equipmentId, 'from role:', roleIdNum);

    const res = await request.delete(`/role/${roleIdNum}/equipment/${equipmentId}`);
    console.log('Remove equipment response:', res);

    if (res.code === 200) {
      ElMessage.success("从角色移除装备成功");
      await loadRoleEquipments(); // 刷新角色装备列表
    } else {
      ElMessage.error(res.message || "从角色移除装备失败");
    }
  } catch (error) {
    handleApiError(error);
  }
}

onMounted(() => {
  console.log('Component mounted and fetching equipments...');
  getEquipments();
});

// 分页事件
function handleSizeChange(size) {
  equipments.value.rows = size;
  getEquipments();
}

function handleCurrentChange(page) {
  equipments.value.page = page;
  getEquipments();
}

// 搜索相关
function onSearch() {
  equipments.value.page = 1; // 重置到第一页
  getEquipments();
}

function onSearchClear() {
  searchQuery.value = '';
  equipments.value.page = 1; // 重置到第一页
  getEquipments();
}

// 新增装备
const addFormRef = ref(null);
async function addEquipment() {
  try {
    const res = await request.post("/equipment", newEquipment.value);
    if (res.code === 200) {
      ElMessage.success("新增装备成功");
      await getEquipments(); // 添加 await
      addEquipmentDialogVisible.value = false;
      newEquipment.value = { name: "", attributeModifier: "", appearance: "" };
    } else {
      ElMessage.error(res.message || "新增装备失败");
    }
  } catch (error) {
    handleApiError(error);
  }
}

// 编辑装备
const editFormRef = ref(null);
function handleEdit(row) {
  currentEquipment.value = { ...row };
  editEquipmentDialogVisible.value = true;
}

async function updateEquipment() {
  try {
    const res = await request.put("/equipment", currentEquipment.value);
    if (res.code === 200) {
      ElMessage.success("更新装备成功");
      await getEquipments(); // 添加 await
      editEquipmentDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || "更新装备失败");
    }
  } catch (error) {
    handleApiError(error);
  }
}

// 删除装备
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确定要删除装备 ${row.name} 吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const res = await request.delete(`/equipment/${row.id}`);
    if (res.code === 200) {
      ElMessage.success("删除装备成功");
      await getEquipments(); // 添加 await
    } else {
      ElMessage.error(res.message || "删除装备失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      handleApiError(error);
    }
  }
}

// 错误处理
function handleApiError(error) {
  console.error('API Error:', error);
  if (error.response) {
    ElMessage.error(error.response.data.message || "请求失败");
  } else if (error.request) {
    ElMessage.error("网络请求超时，请稍后再试");
  } else {
    ElMessage.error("未知错误，请联系管理员");
  }
}
</script>

<style scoped>
.equipment-manage {
  padding: 20px;
}

.role-equipment-manage {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>